package com.jrowny.mediators
{
	import com.jrowny.controls.SpriteElement;
	import com.jrowny.enum.Notes;
	import com.jrowny.proxy.ElementProxy;
	
	import components.ElementsGrid;
	
	import flash.events.Event;
	
	import mx.events.DataGridEvent;
	import mx.events.ListEvent;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	public class ElementsGridMediator extends Mediator
	{
		public static const NAME:String = "ElementsGridMediator";
		
		public var elementProxy:ElementProxy;
		public function ElementsGridMediator(viewComponent:Object=null)
		{
			super(NAME, viewComponent);
			elementProxy = facade.retrieveProxy(ElementProxy.NAME) as ElementProxy;
			elementsGrid.dgElements.dataProvider = elementProxy.elements;
			elementsGrid.dgElements.addEventListener(ListEvent.CHANGE,onChange);
			elementsGrid.dgElements.addEventListener(DataGridEvent.ITEM_EDIT_END,onChangeData);			
		}
		
		public function get elementsGrid():ElementsGrid{
			return viewComponent as ElementsGrid;
		}
		/**
		 * view handlers
		 **/
		private function onChange(event:*):void{
			facade.sendNotification(Notes.ELEMENT_SELECTED,elementsGrid.dgElements.selectedItem as SpriteElement);
		}
		private function onChangeData(event:DataGridEvent):void{
			elementsGrid.callLater(something,[elementsGrid.dgElements.selectedItem as SpriteElement,SpriteElement(elementsGrid.dgElements.selectedItem).baseSelector]);
		}
		private function something(elm:SpriteElement,oldSelector:String):void{
			elementProxy.changeElement(elm.baseSelector,oldSelector);
		}
		
		
		/**
		 * handle notifications
		 */
		override public function listNotificationInterests():Array{
			return [Notes.ELEMENT_SELECTED]
		}
		override public function handleNotification(notification:INotification):void{
			switch(notification.getName()){
				case Notes.ELEMENT_SELECTED:
					elementsGrid.dgElements.selectedItem = notification.getBody() as SpriteElement;
				break;
			}
		}
	}
}